package com.ee.chat.api.listener;

import com.ee.chat.api.server.WebSocketServer;
import com.ee.chat.common.util.ConstantsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 消息订阅监听，接听对象
 */
@Component
public class RedisListener implements MessageListener {
    private Logger log = LoggerFactory.getLogger(RedisListener.class);

    @Resource
    WebSocketServer webSocketServer;

    /**
     * 接受发布者的消息
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = new String(message.getChannel());

        if(ConstantsUtil.USER_WS_OPERATION.equals(channel)){
            try {
                //广播用户动态消息
                webSocketServer.broadcastSendMeaages(new String(message.getBody()));
            }catch (IOException e){
                log.error("广播动态消息失败：" + e);
            }
        }
    }

}
